<template>
  <!-- 品牌签约弹窗 -->
  <el-dialog
    v-model="visible"
    :show-close="false"
    :append-to-body="true"
    :before-close="beforeClose"
    :close-on-click-modal="false"
    top="10vh"
    width="70%"
    class="shop-in-category-pup-dialog component-shop-process-brand header-no-padding"
  >
    <div class="popup">
      <div class="title">
        <div class="text">
          {{ $t('shopProcess.applySigningBrand') }}
        </div>
        <div class="tips">
          <span v-if="isFirst">
            {{ $t('shopProcess.preSigned') }}
            <span class="bold">{{ signingCount }}</span>
            {{ $t('shopProcess.piece') }}{{ $t('shopProcess.brand') }}，
          </span>
          <span>{{ $t('shopProcess.chosen') }}&nbsp;</span>
          <span class="bold">{{ (signBrandForm.signBrandList.length + dataForm.customSignBrandList.length) }}</span>
          {{ $t('shopProcess.piece') }}{{ $t('shopProcess.brand') }}，
          {{ $t('shopProcess.mostAdd') }}
          <span class="bold">50</span>
          {{ $t('shopProcess.piece') }}{{ $t('shopProcess.brand') }}
        </div>
        <div
          class="close-btn"
          @click="closePopup"
        >
          <el-icon>
            <Close />
          </el-icon>
        </div>
      </div>
      <div class="content">
        <div class="left-box">
          <div class="search-box">
            <input
              v-model="keyword"
              class="search-input"
              clearable
              :placeholder="$t('product.pleaEntBraName')"
              @keyup.enter="searchBrand"
            >
            <div
              class="search-btn"
              @click="searchBrand"
            >
              <el-icon>
                <Search />
              </el-icon>
            </div>
          </div>
          <div class="brand-box">
            <div class="brand-list">
              <div
                v-for="(item, index) in allBrandList"
                :key="index"
                class="brand-item"
                :class="{'active':item.isSelected===true}"
                @click="addBrand(item, index)"
              >
                <el-tooltip
                  :content="item.name"
                  placement="right"
                  effect="light"
                  :show-after="200"
                >
                  <div class="brand-item-txt">
                    {{ item.name }}
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
        <div class="right-box">
          <div
            class="table-box"
            :class="{'big-tb': !showCustomization}"
          >
            <el-form
              ref="signBrandFormRef"
              :model="signBrandForm"
              @submit.prevent
            >
              <el-table
                :data="signBrandForm.signBrandList"
                :header-cell-style="{height:'50px',background:'#F5F5F5',color:'#000','font-weight': '400'}"
              >
                <el-table-column
                  prop="name"
                  :label="$t('shopProcess.brandName')"
                />
                <el-table-column
                  prop="firstLetter"
                  :label="$t('shopProcess.firstLetter')"
                />
                <el-table-column
                  prop="imgUrl"
                  :label="$t('shopProcess.brandLogo')"
                >
                  <template #default="scope">
                    <ImgShow
                      :src="scope.row.imgUrl"
                      :img-style="{width:'57px',height:'57px'}"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="qualifications"
                  :label="$t('shopProcess.brandQualifications')"
                  width="250px"
                >
                  <template #default="scope">
                    <el-form-item
                      :rules="{ required: true, message: $t('shopProcess.brandQualificationsNotEmpty'), trigger: 'blur' }"
                      :prop="'signBrandList.' + scope.$index + '.qualifications'"
                    >
                      <div
                        :key="scope.row.qualifications"
                        class="business-qual"
                      >
                        <imgs-upload
                          v-model="scope.row.qualifications"
                          :limit="2"
                          :prompt="false"
                          @input="signBrandImgChange(scope.row.qualifications)"
                        />
                      </div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="address"
                  :label="$t('sys.operation')"
                  align="center"
                >
                  <template #default="scope">
                    <div
                      class="default-btn text-btn"
                      @click="deleteBrand(scope.row.brandId, scope.$index)"
                    >
                      {{ $t('text.delBtn') }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
          <div
            v-if="showCustomization"
            class="custom-box"
          >
            <div class="text">
              {{ $t('shopProcess.customBrand') }}
            </div>
            <div
              class="add-btn default-btn"
              @click="addCustomBrand"
            >
              {{ $t('shopProcess.add') }}&nbsp;{{ $t('shopProcess.customBrand') }}
            </div>
          </div>
          <!-- 添加自定义品牌 -->
          <div
            v-if="dataForm.customSignBrandList.length && showCustomization"
            class="table-box"
          >
            <el-form
              ref="bankCartInfoFormRef"
              :model="dataForm"
              :rules="dataForm.customSignBrandRule"
              @submit.prevent
            >
              <el-table
                class="add-bank-info-table"
                :data="dataForm.customSignBrandList"
                :header-cell-style="{height:'50px',background:'#F5F5F5',color:'#000','font-weight': '400'}"
              >
                <el-table-column
                  :label="$t('shopProcess.brandName')"
                  prop="name"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'customSignBrandList.' + scope.$index + '.name'"
                      :rules="dataForm.customSignBrandRule.name"
                    >
                      <el-input
                        v-model="scope.row.name"
                        :placeholder="$t('shopProcess.brandName')"
                        maxlength="30"
                        style="width:100%"
                        @blur="
                          scope.row.name =
                            scope.row.name ?
                              removeHeadAndTailSpaces(scope.row.name) :
                              scope.row.name;verifyBrandName(scope.row.name, scope.$index)
                        "
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="firstLetter"
                  :label="$t('shopProcess.firstLetter')"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'customSignBrandList.' + scope.$index + '.firstLetter'"
                      :rules="dataForm.customSignBrandRule.firstLetter"
                    >
                      <el-input
                        v-model="scope.row.firstLetter"
                        maxlength="1"
                        :placeholder="$t('shopProcess.firstLetter')"
                        style="width:100%"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="imgUrl"
                  :label="$t('shopProcess.brandLogo')"
                >
                  <template #default="scope">
                    <el-form-item
                      :rules="dataForm.customSignBrandRule.logo"
                      :prop="'customSignBrandList.' + scope.$index + '.imgUrl'"
                    >
                      <div class="business-qual">
                        <img-upload
                          v-model="scope.row.imgUrl"
                          @input="imgChange(scope.row.imgUrl)"
                        />
                      </div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="qualifications"
                  :label="$t('shopProcess.brandQualifications')"
                  width="200px"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'customSignBrandList.' + scope.$index + '.qualifications'"
                      :rules="dataForm.customSignBrandRule.qualifications"
                    >
                      <div
                        :key="scope.row.qualifications"
                        class="business-qual"
                      >
                        <imgs-upload
                          v-model="scope.row.qualifications"
                          :limit="2"
                          :prompt="false"
                          @input="imgChange(scope.row.qualifications)"
                        />
                      </div>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="address"
                  :label="$t('sys.operation')"
                  align="center"
                >
                  <template #default="scope">
                    <div
                      class="default-btn text-btn"
                      @click="deleteCustomBrandItem(scope.$index)"
                    >
                      {{ $t('text.delBtn') }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </div>
      </div>

      <div class="btn-row foot-btn">
        <div
          class="default-btn"
          @click="closePopup"
        >
          {{ $t('homes.no') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="comfirmSubmit"
        >
          {{ $t('homes.yes') }}
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { removeHeadAndTailSpaces } from '@/utils/validate.js'
import { Debounce } from '@/utils/debounce'
import { ElMessage } from 'element-plus'

const props = defineProps({
  /**
   * 是否从店铺信息申请签约
   * applyForSign=true时，请求可以签约的平台品牌列表（已经签约的平台品牌不会返回）
   */
  applyForSign: {
    type: Boolean,
    default: false
  },
  signingCount: {
    type: Number,
    default: 0
  },
  isFirst: {
    type: Boolean,
    default: true
  },
  brandNameList: {
    type: Array,
    default: () => {}
  }
})
const emit = defineEmits(['closePopup', 'closePopup'])

// 图片前缀
const keyword = ref('')
const signBrandForm = reactive({ signBrandList: [] })

const validateFirstLetter = (rule, value, callback) => {
  const regexp = /^[A-Z]{1}$/
  if (!regexp.test(value)) {
    callback(new Error($t('product.firstLetterErrorTips')))
  } else {
    callback()
  }
}

const dataForm = reactive({
  customSignBrandList: [],
  customSignBrandRule: {
    name: [
      { required: true, message: $t('publics.noNull'), trigger: 'blur' },
      { min: 1, max: 50, message: $t('product.brandNameErrorTips'), trigger: 'blur' }
    ],
    firstLetter: [
      { required: true, message: $t('publics.noNull'), trigger: 'blur' },
      { validator: validateFirstLetter, trigger: 'blur' }
    ],
    logo: [
      { required: true, message: $t('product.brandLogoNotEmpty'), trigger: 'blur' }
    ],
    qualifications: [
      { required: true, message: $t('shopProcess.brandQualificationsNotEmpty'), trigger: 'blur' }
    ]
  }
})

let brandNameInputList = []
watch(() => props.brandNameList, (val) => {
  brandNameInputList = val
})

const visible = ref(false)
// 是否显示自定义品牌
const showCustomization = ref(true)
// 初始化
const init = (pageType) => {
  visible.value = true
  if (pageType === 'editor') {
    showCustomization.value = false
  }
  getPlatformBrand()
  if (!props.applyForSign) {
    getSignBrandList()
  }
}

const bankCartInfoFormRef = ref(null)
/**
 * 上传图片的值发生改变，重新校验表单
 */
const imgChange = (value) => {
  if (value) {
    bankCartInfoFormRef.value?.validate().catch(() => { })
  }
}

const signBrandFormRef = ref(null)
const signBrandImgChange = (value) => {
  if (value) {
    signBrandFormRef.value?.validate().catch(() => { })
  }
}

/**
 * 获取平台全部品牌
 */
const getPlatformBrand = () => {
  http({
    url: props.applyForSign ? http.adornUrl('/shop/signingAuditing/listApplySigningBrand') : http.adornUrl('/admin/brand/list'),
    method: 'get',
    params: http.adornParams({ name: keyword.value, status: 1 })
  }).then(({ data }) => {
    const signBrandList = signBrandForm.signBrandList
    const allBrandList = data
    if (showCustomization.value) {
      data.forEach(item => {
        brandNameInputList.push(item.name)
      })
      brandNameInputList = [...new Set(brandNameInputList)]
    }
    brandEcho(allBrandList, signBrandList)
  })
}

// 校验品牌名称是否重复
const verifyBrandName = (value, index) => {
  const nameList = dataForm.customSignBrandList.filter((item, i) => index !== i && item.name).map((item) => {
    return item.name
  })
  const bankNameList = [...new Set(nameList), ...new Set(brandNameInputList)]
  if (bankNameList.indexOf(value) >= 0) {
    const data = dataForm.customSignBrandList[index]
    data.name = ''
    dataForm.customSignBrandList[index] = data
    ElMessage({
      message: $t('shopProcess.brandNameRepeatTip'),
      type: 'error',
      duration: 1000
    })
  }
}

const allBrandList = ref([])
/**
 * 左侧回显选中品牌或已签约品牌
 * @param {Array} allBrandListPar 全部品牌
 * @param {Array} signBrandList 选中品牌和已签约品牌
 */
const brandEcho = (allBrandListPar, signBrandList) => {
  allBrandListPar.forEach(item => {
    item.isSelected = false
  })
  if (signBrandList.length > 0 && allBrandListPar.length > 0) {
    for (let i = 0; i < signBrandList.length; i++) {
      for (let j = 0; j < allBrandListPar.length; j++) {
        if (signBrandList[i].brandId === allBrandListPar[j].brandId) {
          allBrandListPar[j].isSelected = true
          break
        }
      }
    }
  }
  allBrandList.value = allBrandListPar
}

/**
 * 获取签约品牌列表
 */
const getSignBrandList = () => {
  http({
    url: http.adornUrl('/admin/brand/listSigningBrand'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    signBrandForm.signBrandList = data.platformBrandList
    dataForm.customSignBrandList = data.customizeBrandList
    const signBrandList = signBrandForm.signBrandList
    brandEcho(allBrandList.value, signBrandList)
  })
}

/**
 * 搜索品牌
 */
const searchBrand = () => {
  getPlatformBrand()
}

/**
 * 选中添加品牌
 */
const addBrand = (brandObj, index) => {
  const length = signBrandForm.signBrandList.length + dataForm.customSignBrandList.length + props.signingCount
  if (length >= 50) {
    ElMessage.warning($t('shopProcess.brandMaxLimitTips'))
  } else {
    if (brandObj.isSelected === false) {
      signBrandForm.signBrandList.push(brandObj)
    }
    allBrandList.value[index].isSelected = true
  }
}

/**
 * 添加自定义品牌
 */
const addCustomBrand = () => {
  const length = signBrandForm.signBrandList.length + dataForm.customSignBrandList.length
  if (length >= 50) {
    ElMessage.warning($t('shopProcess.brandMaxLimitTips'))
    return
  }
  dataForm.customSignBrandList.push(
    {
      name: '',
      // alias: '', // 品牌别名
      imgUrl: '',
      qualifications: ''
    }
  )
}

/**
 * 删除自定义品牌项
 */
const deleteCustomBrandItem = (index) => {
  dataForm.customSignBrandList.splice(index, 1)
}

/**
 * 删除选中品牌
 * @param {Number} id 品牌id
 * @param {Number} index 选中品牌列表索引
 */
const deleteBrand = (id, index) => {
  // 去除选中样式
  allBrandList.value.forEach(brandItem => {
    if (brandItem.brandId === id) {
      brandItem.isSelected = false
    }
  })
  signBrandForm.signBrandList.splice(index, 1)
}

let submit = false
/**
 * 签约品牌
 */
const signBrand = () => {
  if (submit) {
    return
  }
  submit = true
  const params = {
    platformBrandList: [],
    customizeBrandList: []
  }
  signBrandForm.signBrandList.forEach(item => {
    const param = {
      brandId: item.brandId,
      name: item.name,
      imgUrl: item.imgUrl,
      qualifications: item.qualifications
    }
    params.platformBrandList.push(param)
  })
  params.customizeBrandList = dataForm.customSignBrandList
  http({
    url: props.applyForSign ? http.adornUrl('/shop/signingAuditing/addSigningBrand') : http.adornUrl('/admin/brand/signing'),
    method: 'post',
    data: http.adornData(params)
  }).then(() => {
    ElMessage({
      message: props.applyForSign ? $t('shopProcess.brandAddSuccess') : $t('shopProcess.brandSaveSuccess'),
      type: 'success',
      duration: 1000
    })
    closePopup()
  }).finally(() => {
    submit = false
  })
}

/**
 * 确认提交
 */
const comfirmSubmit = Debounce(async () => {
  let pass = true
  if (signBrandForm.signBrandList.length) {
    await signBrandFormRef.value?.validate((valid) => {
      if (!valid) {
        pass = false
      }
    })
  }
  if (dataForm.customSignBrandList.length) {
    await bankCartInfoFormRef.value?.validate((valid) => {
      if (!valid) {
        pass = false
        return
      }
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.imgUrl)) {
        ElMessage.error($t('product.brandLogoNotEmpty'))
        pass = false
        return
      }
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.qualifications)) {
        ElMessage.error($t('shopProcess.brandQualificationsNotEmpty'))
        pass = false
      }
    })
  }
  if (pass) {
    signBrand()
  }
}, 1500)

/**
 * 关闭弹窗
 */
const closePopup = () => {
  emit('closePopup', 'brand')
}
const beforeClose = (done) => {
  emit('closePopup', 'brand')
  done()
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
@use "index";
</style>
